package dataview

import (
	"fmt"
	channel_define "go-iot-gateway/internal/channel/define"
	"go-iot-gateway/internal/conf_table"
	conf_table_define "go-iot-gateway/internal/conf_table/define"
	"go-iot-gateway/internal/logger"
	"go-iot-gateway/internal/storage"
	storage_define "go-iot-gateway/internal/storage/define"
	"sort"
	"strings"
	"time"
)

func DeviceDataView(devId string) string {
	return strings.ReplaceAll(dataViewHtmlTemp, "%{tbody}", tbody(devId))
}

func tbody(devId string) string {

	if strings.TrimSpace(devId) == "" {
		return ""

	}

	result := ""

	deviceInfo, err := conf_table.FindAllDeviceByDevId(devId)
	if err != nil {
		return ""
	}

	isTransfer := deviceInfo.ChannelInfo.IsTransfer()
	isThingsobard := deviceInfo.ChannelInfo.Chl_protocol == channel_define.THINGSBOARD_MQTT_CLIENT
	tagInfos := conf_table.FindAllTagByDeviceId(strings.TrimSpace(devId))

	sort.Slice(tagInfos, func(i, j int) bool {
		return tagInfos[i].Id < tagInfos[j].Id
	})
	for _, tag := range tagInfos {
		var oriTag *conf_table_define.TagInfo
		var val storage_define.ValObject
		var err error
		if isTransfer {
			oriTag, err = conf_table.FindAllTagByTagId(tag.Ori_tag_id)
			if err == nil {
				val, err = storage.FindLatestVal(oriTag.Tag_name)
			}
		} else {
			val, err = storage.FindLatestVal(tag.Tag_name)
		}

		if err != nil || val == nil {
			logger.Web().Warn("无法查询到 值 error", err)
			continue
		}
		//0 好 , 100 坏 ， 50 初始化中
		qos := "<span style='color:green'>好</span>"
		if val.Qos() == 100 {
			qos = "<span style='color:red'>坏</span>"
		} else if val.Qos() == 50 {
			qos = "<span>初始化中</span>"
		}

		strVal := "nil"
		if val.Val() == nil {
			strVal = "nil"
		} else if _, ok := val.Val().(float64); ok {
			strVal = fmt.Sprintf("%.14g", val.Val())
		} else {
			strVal = fmt.Sprintf("%v", val.Val())
		}

		ts := time.UnixMilli(val.Ts()).Format("2006-01-02 15:04:05")
		if isThingsobard {
			result += fmt.Sprintf(" <tr> <td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td> <td>%s</td> <td>%s</td></tr>",
				tag.DeviceInfo.Dev_name, tag.Tag_desc, strVal, oriTag.DeviceInfo.Dev_name+" | "+oriTag.Tag_name, qos, ts, tag.DataTypeStr())
		} else {
			result += fmt.Sprintf(" <tr> <td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td> <td>%s</td> <td>%s</td></tr>",
				tag.DeviceInfo.Dev_name, tag.Tag_name, strVal, tag.Tag_desc, qos, ts, tag.DataTypeStr())
		}

	}

	return result

}

var dataViewHtmlTemp = `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8">
    <style>
        table {
            width: 100%;
            border-collapse: collapse;
        }
        table caption {
            font-size: 2em;
            font-weight: bold;
            margin: 1em 0;
        }
        th, td {
            border: 1px solid #999;
            /*text-align: center;*/
            min-width: 100px;
            padding: 3px 0;
        }
        table thead tr {
            background-color: #008c8c;
            color: #fff;
        }
        table tbody tr:nth-child(odd) {
            background-color: #eee;
        }
        table tbody tr:hover {
            background-color: #ccc;
        }
        table tbody tr td:first-child {
            color: green;
        }
		body {
            margin: 1px
        }
    </style></head><body><table><thead>
    <tr>
        <td>设备</td>
        <td>key</td>
        <td>值</td>
        <td>描述</td>
        <td>质量</td>
        <td>时间</td>
        <td>数据类型</td>
    </tr></thead><tbody>%{tbody}</tbody></table></body></html>`
